/*
 * Copyright 2010 Dovado FZ-LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*NOTE: If you want to test the MAP API's (with a debug key) then this is howto do it:
 *keytool -list -alias androiddebugkey -keystore debug.keystore -storepass android -keypass android
 *
 *you get the following output:
 *androiddebugkey, Apr 14, 2010, PrivateKeyEntry, 
 *Certificate fingerprint (MD5): XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:X
 *
 *Paste the MD5 (XX:XX...) into http://code.google.com/android/maps-api-signup.html
 *Put the obtained key in map.xml (replace android:apiKey="ADD_KEY_HERE" with android:apiKey="MYKEY")
 *
 */
package com.dovado.dovadoremote;

import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class Map extends MapActivity {

	class MapOverlay extends com.google.android.maps.Overlay {
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);

			/*
			 * translate the GeoPoint to screen pixels
			 */
			Point screenPts = new Point();
			mapView.getProjection().toPixels(p, screenPts);

			/*
			 * add the marker
			 */

			canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);

			return true;
		}
	}

	static MapView mapView;
	static MapController mc;
	static GeoPoint p;
	private static Bitmap bmp;

	public static void updateCoordinates() {
		/*
		 * This is very ugly. If we call this from the SYNC without having
		 * visited the map-tab yet then the map won't be loaded and it will
		 * crash. Temporarily fixed with a try/catch.
		 */
		try {
			p = new GeoPoint(Info.getGPSLat(), Info.getGPSLong());
			// zoom to the whole world if bogus coordinates are used:
			if (Info.getIsBogusCoordinates()) {
				mc.setZoom(2);
			} else {
				mc.setZoom(11);
			}
			mc.setCenter(p);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * TODO: remove
	 */
	protected void alertbox(String title, String mymessage) {
		new AlertDialog.Builder(this).setMessage(mymessage).setTitle(title)
				.setCancelable(true).setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).show();
	}

	private void initialize(String in_from) {
		/*
		 * Show "map not available" if using a 3GN:
		 */
		if (Communicator.getRouterModel().contains("3GN")) {
			if (in_from.contains("fromresume")) {
				alertbox("Not available", getResources().getString(
						R.string.map_notsupported));
			}
			TextView tmpText = (TextView) findViewById(R.id.MapErrorText);
			tmpText
					.setText(getResources()
							.getString(R.string.map_notsupported));
			findViewById(R.id.MapErrorText).setVisibility(0);
		}

		/*
		 * Show "not connected"if that's the case:
		 */
		else if (!DAAPP.getHasSynced()) {
			/*
			 * if (in_from.contains("fromresume")){ alertbox("Not available",
			 * getResources().getString(R.string.map_notconnected)); }
			 */
			TextView tmpText = (TextView) findViewById(R.id.MapErrorText);
			tmpText
					.setText(getResources()
							.getString(R.string.map_notconnected));
			findViewById(R.id.MapErrorText).setVisibility(0);
		}
		/*
		 * if the router supports positioning and has synced then do not show
		 * errormessage
		 */
		else {
			if (findViewById(R.id.MapErrorText).getVisibility() != 4) {
				findViewById(R.id.MapErrorText).setVisibility(4);
			}
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		mapView = (MapView) findViewById(R.id.mapView);
		mc = mapView.getController();
		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
		View zoomView = mapView.getZoomControls();

		zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
		mapView.displayZoomControls(true);

		MapOverlay mapOverlay = new MapOverlay();
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.clear();
		listOfOverlays.add(mapOverlay);
		updateCoordinates();
		bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

	}

	/*
	 * If the user presses the 'back'-button (we can add some more functionality
	 * here
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent i = new Intent();
			i.setAction(Intent.ACTION_MAIN);
			i.addCategory(Intent.CATEGORY_HOME);
			this.startActivity(i);
			return true;
		}
		return false;
	}

	/*
	 * Re-initialize on resume:
	 */
	@Override
	public void onResume() {
		super.onResume();

		initialize("fromresume");

	}

}